package cn.sourcespro.shiro.security;

import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.mgt.DefaultSessionStorageEvaluator;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.subject.SubjectContext;
import org.apache.shiro.web.mgt.DefaultWebSessionStorageEvaluator;
import org.apache.shiro.web.mgt.DefaultWebSubjectFactory;

/**
 * security
 *
 * @author zhanghaowei
 * @date 2018/7/20
 */
public class StatelessDefaultSubjectFactory extends DefaultWebSubjectFactory {

    private final DefaultSessionStorageEvaluator storageEvaluator;

    public StatelessDefaultSubjectFactory(DefaultSessionStorageEvaluator storageEvaluator) {
        this.storageEvaluator = storageEvaluator;
    }

    @Override
    public Subject createSubject(SubjectContext context) {
        AuthenticationToken authenticationToken = context.getAuthenticationToken();
        if (authenticationToken instanceof JwtToken) {
            //当token为HmacToken时， 不创建 session
            context.setSessionCreationEnabled(false);
            // 不持久化session
            this.storageEvaluator.setSessionStorageEnabled(false);
        }
        if (authenticationToken instanceof UpToken) {
            //当token为UpToken时， 不创建 session
            context.setSessionCreationEnabled(false);
            // 不持久化session
            this.storageEvaluator.setSessionStorageEnabled(false);
        }
        return super.createSubject(context);
    }
}
